package com.jwgf.smarowindingmachine_unity.ui;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.jwgf.Half485.fxthreadpool.FxPLCData;
import com.jwgf.Half485.modbusthreadpool.ModbusCommandManager;
import com.jwgf.Half485.modbusthreadpool.ModbusUtils;
import com.jwgf.Half485.modbusthreadpool.PLCData;
import com.jwgf.common.Utility;
import com.jwgf.common.ViewCache;
import com.jwgf.smarowindingmachine_unity.R;
import com.jwgf.smarowindingmachine_unity.logic.CommandGenerator;
import com.jwgf.smarowindingmachine_unity.logic.MachineParameterSharedPreference;
import com.jwgf.smarowindingmachine_unity.logic.SmaroWindingMachineDataAccessRules;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ParameterSettingSystemParameterFragment extends BaseFragment implements
        OnClickListener, OnEditorActionListener, OnFocusChangeListener {
    public static final String fragmentTag = "ParameterSettingSystemParameterFragment";

    private MachineParameterSharedPreference sp = MachineParameterSharedPreference.getInstance();

    private TextView count_unit_value;
    private TextView length_unit_value;
    private TextView weight_unit_value;
    private TextView machine_drive_value;
    private TextView yarn_cleaner_value;

    private EditText machine_num_edit;
    private EditText serial_num_edit;
    private EditText machine_unlock_edit;

    private ImageButton btn_count_unit;
    private ImageButton btn_length_unit;
    private ImageButton btn_weight_unit;
    private ImageButton btn_machine_drive;
    private ImageButton btn_yarn_cleaner;

    private Button btn_mitsubishi;
    private Button btn_siemens;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = ViewCache.getInstance().getView(R.layout.fragment_parameter_setting_system_parameter);
//        View v = inflater.inflate(R.layout.fragment_parameter_setting_system_parameter, container, false);
        initialViews(v);
        EventBus.getDefault().register(this);
        updateViews();
        return v;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            EventBus.getDefault().unregister(this);
        } else {
            updateViews();
            if (!EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().register(this);
            }
        }
    }

    private void initialViews(View v) {

        btn_count_unit = (ImageButton) v.findViewById(R.id.btn_count_unit);
        btn_count_unit.setOnClickListener(this);

        btn_length_unit = (ImageButton) v.findViewById(R.id.btn_length_unit);
        btn_length_unit.setOnClickListener(this);

        btn_weight_unit = (ImageButton) v.findViewById(R.id.btn_weight_unit);
        btn_weight_unit.setOnClickListener(this);

        btn_machine_drive = (ImageButton) v.findViewById(R.id.btn_machine_drive);
        btn_machine_drive.setOnClickListener(this);

        btn_yarn_cleaner = (ImageButton) v.findViewById(R.id.btn_yarn_cleaner);
        btn_yarn_cleaner.setOnClickListener(this);

        btn_mitsubishi = (Button) v.findViewById(R.id.mitsubishi_btn);
        btn_mitsubishi.setOnClickListener(this);

        btn_siemens = (Button) v.findViewById(R.id.siemens_btn);
        btn_siemens.setOnClickListener(this);

        count_unit_value = (TextView) v.findViewById(R.id.count_unit_value);
        length_unit_value = (TextView) v.findViewById(R.id.length_unit_value);
        weight_unit_value = (TextView) v.findViewById(R.id.weight_unit_value);
        machine_drive_value = (TextView) v.findViewById(R.id.machine_drive_value);
        yarn_cleaner_value = (TextView) v.findViewById(R.id.yarn_cleaner_value);

        machine_num_edit = initEdittextOnCreate(v, R.id.machine_num_value);
        serial_num_edit = initEdittextOnCreate(v, R.id.serial_num_value);
        machine_unlock_edit = initEdittextOnCreate(v, R.id.machine_unlock_value);
    }

    private void updateViews() {
        machine_num_edit.setText(sp.getValue(MachineParameterSharedPreference.SYSTEM_MACHINE_NUM, "1"));
        serial_num_edit.setText(sp.getValue(MachineParameterSharedPreference.SYSTEM_SERIAL_NUM, "00000001"));
        int lockState = PLCData.getInstance().getHoldingRegister(1, 2500) & 0x200;
        String strLockState = lockState == 0 ? "" : ".";
        machine_unlock_edit.setText(strLockState);

        if (sp.getValue(MachineParameterSharedPreference.SYSTEM_COUNT_UNIT, "0").equals("0")) {
            count_unit_value.setText(R.string.behind_ne);
        } else if (sp.getValue(MachineParameterSharedPreference.SYSTEM_COUNT_UNIT, "0").equals("1")) {
            count_unit_value.setText(R.string.behind_nm);
        } else {
            count_unit_value.setText(R.string.behind_tex);
        }

        if (sp.getValue(MachineParameterSharedPreference.SYSTEM_LENGTH_UNIT, "0").equals("0")) {
            length_unit_value.setText(R.string.ss_lengthUnit);
        } else {
            length_unit_value.setText(R.string.behind_y);
        }

        if (sp.getValue(MachineParameterSharedPreference.SYSTEM_WEIGHT_UNIT, "0").equals("0")) {
            weight_unit_value.setText(R.string.ss_weightUnit);
        } else {
            weight_unit_value.setText(R.string.ss_weightUnit_eng);
        }

        if (sp.getValue(MachineParameterSharedPreference.SYSTEM_MACHINE_DRIVE, "0").equals("0")) {
            machine_drive_value.setText(R.string.left);
        } else {
            machine_drive_value.setText(R.string.right);
        }

        if (sp.getValue(MachineParameterSharedPreference.SYSTEM_YARN_CLEANER, "0").equals("0")) {
            yarn_cleaner_value.setText("USTER");
        } else if (sp.getValue(MachineParameterSharedPreference.SYSTEM_YARN_CLEANER, "0").equals("1")) {
            yarn_cleaner_value.setText("keisokki");
        } else if (sp.getValue(MachineParameterSharedPreference.SYSTEM_YARN_CLEANER, "0").equals("2")) {
            yarn_cleaner_value.setText("Loepfe");
        } else {
            yarn_cleaner_value.setText(R.string.changling);
        }

        if (sp.getValue(MachineParameterSharedPreference.PLC_TYPE, "0").equals("0")) {
            btn_siemens.setSelected(true);
            btn_mitsubishi.setSelected(false);
        } else {
            btn_siemens.setSelected(false);
            btn_mitsubishi.setSelected(true);
        }
    }

    private EditText initEdittextOnCreate(View v, int id) {
        EditText editText = (EditText) v.findViewById(id);
        editText.setSelectAllOnFocus(true);
        editText.setOnFocusChangeListener(this);
        editText.setOnEditorActionListener(this);
        editText.setBackgroundDrawable(null);
        return editText;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_count_unit: {
                final String[] content = getResources().getStringArray(R.array.count_unit);
                ListDialogFragment listDialog = new ListDialogFragment();
                Bundle bd = new Bundle();
                bd.putStringArray(ListDialogFragment.ARRAY, content);
                listDialog.setArguments(bd);
                listDialog.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        count_unit_value.setText(content[position]);
                        sp.setValue(MachineParameterSharedPreference.SYSTEM_COUNT_UNIT, String.valueOf(position));
                    }
                });
                listDialog.show(getFragmentManager(), "listDialog");
                break;
            }

            case R.id.btn_length_unit: {
                final String[] content = getResources().getStringArray(R.array.length_unit);
                ListDialogFragment listDialog = new ListDialogFragment();
                Bundle bd = new Bundle();
                bd.putStringArray(ListDialogFragment.ARRAY, content);
                listDialog.setArguments(bd);
                listDialog.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        length_unit_value.setText(content[position]);
                        sp.setValue(MachineParameterSharedPreference.SYSTEM_LENGTH_UNIT, String.valueOf(position));
                    }
                });
                listDialog.show(getFragmentManager(), "listDialog");
                break;
            }

            case R.id.btn_weight_unit: {
                final String[] content = getResources().getStringArray(R.array.weight_unit);
                ListDialogFragment listDialog = new ListDialogFragment();
                Bundle bd = new Bundle();
                bd.putStringArray(ListDialogFragment.ARRAY, content);
                listDialog.setArguments(bd);
                listDialog.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        weight_unit_value.setText(content[position]);
                        sp.setValue(MachineParameterSharedPreference.SYSTEM_WEIGHT_UNIT, String.valueOf(position));
                    }
                });
                listDialog.show(getFragmentManager(), "listDialog");
                break;
            }

            case R.id.btn_machine_drive: {
                final String[] content = getResources().getStringArray(R.array.machine_drive);
                ListDialogFragment listDialog = new ListDialogFragment();
                Bundle bd = new Bundle();
                bd.putStringArray(ListDialogFragment.ARRAY, content);
                listDialog.setArguments(bd);
                listDialog.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        machine_drive_value.setText(content[position]);
                        sp.setValue(MachineParameterSharedPreference.SYSTEM_MACHINE_DRIVE, String.valueOf(position));
                        byte[] datai = new byte[2];
                        datai[0] = (byte) ((position & 0xff00) >> 8);
                        datai[1] = (byte) (position & 0xff);
                        SmaroWindingMachineActivity.canHandStack.putPriorityCmd(
                                sp.createCanCmd75(0x75, 0x01, 500, String.valueOf(position)));//215
//						SmaroWindingMachineActivity.half485Stack
//								.putPriorityCmd(ModbusUtils.createWriteRegisterCmd(
//										(byte) 1, 63, datai));//420
                        ModbusCommandManager.getInstance()
                                .putPriorityCmd(CommandGenerator.createWriteCommand(
                                        (byte) 1, 63, datai));//420
                    }
                });
                listDialog.show(getFragmentManager(), "listDialog");
                break;
            }

            case R.id.btn_yarn_cleaner: {
                final String[] content = getResources().getStringArray(R.array.yarn_cleaner);
                ListDialogFragment listDialog = new ListDialogFragment();
                Bundle bd = new Bundle();
                bd.putStringArray(ListDialogFragment.ARRAY, content);
                listDialog.setArguments(bd);
                listDialog.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        yarn_cleaner_value.setText(content[position]);
                        sp.setValue(MachineParameterSharedPreference.SYSTEM_YARN_CLEANER, String.valueOf(position));
                    }
                });
                listDialog.show(getFragmentManager(), "listDialog");
                break;
            }
            case R.id.siemens_btn:
                sp.setValue(MachineParameterSharedPreference.PLC_TYPE, "0");
                btn_siemens.setSelected(true);
                btn_mitsubishi.setSelected(false);
                break;
            case R.id.mitsubishi_btn:
                sp.setValue(MachineParameterSharedPreference.PLC_TYPE, "1");
                btn_siemens.setSelected(false);
                btn_mitsubishi.setSelected(true);
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            String strValue = v.getText().toString();
            if (strValue.equals("")) {
                return false;
            }
            boolean isValid = false;
            String key = "";

            switch (v.getId()) {
                case R.id.machine_num_value:
                    key = MachineParameterSharedPreference.SYSTEM_MACHINE_NUM;
                    isValid = SmaroWindingMachineDataAccessRules.getInstance().isBetween(key, strValue);
                    if (isValid) {
                        sp.setValue(key, strValue);
                    }
                    break;

                case R.id.serial_num_value:
                    key = MachineParameterSharedPreference.SYSTEM_SERIAL_NUM;
//				isValid = SmaroWindingMachineDataAccessRules.getInstance().isBetween(key, strValue);
//				if (isValid) {
                    sp.setValue(key, strValue);
//				}
                    break;

                case R.id.machine_unlock_value:
                    int lockState = PLCData.getInstance().getHoldingRegister(1, 2500) & 0x2;
                    String strLockState = lockState == 0 ? "" : ".";
                    v.setText(strLockState);
                    Pattern pattern = Pattern.compile("[0-9]+");
                    Matcher matcher = pattern.matcher(strValue);
                    boolean result = matcher.matches();
                    if (result) {
                        byte[] cmd = Utility.ByteArrayUtils.short2ByteArray(Short.valueOf(strValue));
                        ModbusCommandManager.getInstance().putPriorityCmd(ModbusUtils.createWriteRegisterCmd((byte) 1, 7, cmd));
                    } else {
                        Toast.makeText(getActivity(), "请输入数字！", Toast.LENGTH_SHORT).show();
                    }
                    break;

                default:
                    break;
            }

            if (!TextUtils.isEmpty(key) && !key.equals(MachineParameterSharedPreference.SYSTEM_SERIAL_NUM)) {
                if (!isValid) {
                    String max = SmaroWindingMachineDataAccessRules.getInstance().getDataAccessRule(key).getMax();
                    String min = SmaroWindingMachineDataAccessRules.getInstance().getDataAccessRule(key).getMin();
                    String warning = getResources().getString(R.string.range_warning);
                    warning = String.format(warning, min, max);
                    WarningDialog.show(getActivity(), warning);
                    updateViews();
                }
            }
        }
        return false;
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        int id = v.getId();
        switch (id) {
            case R.id.machine_num_value:
                if (!hasFocus) {
                    machine_num_edit.setText(
                            sp.getValue(MachineParameterSharedPreference.SYSTEM_MACHINE_NUM, "1"));
                }
                break;
            case R.id.serial_num_value:
                if (!hasFocus) {
                    serial_num_edit.setText(
                            sp.getValue(MachineParameterSharedPreference.SYSTEM_SERIAL_NUM, "1"));
                }
                break;
            case R.id.machine_unlock_value:
                if (!hasFocus) {
                    int lockState = PLCData.getInstance().getHoldingRegister(1, 2500) & 0x2;
                    String strLockState = lockState == 0 ? "" : ".";
                    machine_unlock_edit.setText(strLockState);
                }
                break;
            default:
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onHoldingRegisterEvent(PLCData.HoldingRegister holding) {
        int addr = holding.addr;
        int value = holding.value;
        switch (addr) {
            case 2500:
                int lockState = PLCData.getInstance().getHoldingRegister(1, 2500) & 0x2;
                String strLockState = lockState == 0 ? "" : ".";
                machine_unlock_edit.setText(strLockState);
                break;
            case 63:
            case 155:
                final String[] content = getResources().getStringArray(R.array.machine_drive);
                machine_drive_value.setText(content[value]);
                break;
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDRegisterEvent(FxPLCData.DRegister dRegister) {
        int addr = dRegister.fxPLCData.getKey(dRegister);
        int value = dRegister.value;
        switch (addr) {
            case (2 << 16 | 726):
                machine_unlock_edit.setText(String.valueOf(value));
                break;
            case (4 << 16 | 420):
            case (6 << 16 | 215):
                final String[] content = getResources().getStringArray(R.array.machine_drive);
                machine_drive_value.setText(content[value]);
                break;
        }

    }

}